
package plugin_market

import (
	"context"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/plugin_market"
    plugin_marketReq "github.com/flipped-aurora/gin-vue-admin/server/model/plugin_market/request"
    "gorm.io/gorm"
)

type PluginUsageStatsService struct {}
// CreatePluginUsageStats 创建插件使用统计记录
// Author [yourname](https://github.com/yourname)
func (pusService *PluginUsageStatsService) CreatePluginUsageStats(ctx context.Context, pus *plugin_market.PluginUsageStats) (err error) {
	err = global.GVA_DB.Create(pus).Error
	return err
}

// DeletePluginUsageStats 删除插件使用统计记录
// Author [yourname](https://github.com/yourname)
func (pusService *PluginUsageStatsService)DeletePluginUsageStats(ctx context.Context, ID string,userID uint) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
	    if err := tx.Model(&plugin_market.PluginUsageStats{}).Where("id = ?", ID).Update("deleted_by", userID).Error; err != nil {
              return err
        }
        if err = tx.Delete(&plugin_market.PluginUsageStats{},"id = ?",ID).Error; err != nil {
              return err
        }
        return nil
	})
	return err
}

// DeletePluginUsageStatsByIds 批量删除插件使用统计记录
// Author [yourname](https://github.com/yourname)
func (pusService *PluginUsageStatsService)DeletePluginUsageStatsByIds(ctx context.Context, IDs []string,deleted_by uint) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
	    if err := tx.Model(&plugin_market.PluginUsageStats{}).Where("id in ?", IDs).Update("deleted_by", deleted_by).Error; err != nil {
            return err
        }
        if err := tx.Where("id in ?", IDs).Delete(&plugin_market.PluginUsageStats{}).Error; err != nil {
            return err
        }
        return nil
    })
	return err
}

// UpdatePluginUsageStats 更新插件使用统计记录
// Author [yourname](https://github.com/yourname)
func (pusService *PluginUsageStatsService)UpdatePluginUsageStats(ctx context.Context, pus plugin_market.PluginUsageStats) (err error) {
	err = global.GVA_DB.Model(&plugin_market.PluginUsageStats{}).Where("id = ?",pus.ID).Updates(&pus).Error
	return err
}

// GetPluginUsageStats 根据ID获取插件使用统计记录
// Author [yourname](https://github.com/yourname)
func (pusService *PluginUsageStatsService)GetPluginUsageStats(ctx context.Context, ID string) (pus plugin_market.PluginUsageStats, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&pus).Error
	return
}
// GetPluginUsageStatsInfoList 分页获取插件使用统计记录
// Author [yourname](https://github.com/yourname)
func (pusService *PluginUsageStatsService)GetPluginUsageStatsInfoList(ctx context.Context, info plugin_marketReq.PluginUsageStatsSearch) (list []plugin_market.PluginUsageStats, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&plugin_market.PluginUsageStats{})
    var puss []plugin_market.PluginUsageStats
    // 如果有条件搜索 下方会自动创建搜索语句
    if len(info.CreatedAtRange) == 2 {
     db = db.Where("created_at BETWEEN ? AND ?", info.CreatedAtRange[0], info.CreatedAtRange[1])
    }
    
    if info.UserId != nil {
        db = db.Where("user_id = ?", *info.UserId)
    }
    if info.PluginId != nil {
        db = db.Where("plugin_id = ?", *info.PluginId)
    }
    if info.AccessCount != nil {
        db = db.Where("access_count >= ?", *info.AccessCount)
    }
    if info.UsageDuration != nil {
        db = db.Where("usage_duration >= ?", *info.UsageDuration)
    }
			if len(info.LastAccessTimeRange) == 2 {
				db = db.Where("last_access_time BETWEEN ? AND ? ", info.LastAccessTimeRange[0], info.LastAccessTimeRange[1])
			}
			if len(info.StatDateRange) == 2 {
				db = db.Where("stat_date BETWEEN ? AND ? ", info.StatDateRange[0], info.StatDateRange[1])
			}
    if info.IsActive != nil {
        db = db.Where("is_active = ?", *info.IsActive)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }
        var OrderStr string
        orderMap := make(map[string]bool)
           orderMap["id"] = true
           orderMap["created_at"] = true
         	orderMap["access_count"] = true
         	orderMap["usage_duration"] = true
         	orderMap["last_access_time"] = true
         	orderMap["stat_date"] = true
       if orderMap[info.Sort] {
          OrderStr = info.Sort
          if info.Order == "descending" {
             OrderStr = OrderStr + " desc"
          }
          db = db.Order(OrderStr)
       }

	if limit != 0 {
       db = db.Limit(limit).Offset(offset)
    }

	err = db.Find(&puss).Error
	return  puss, total, err
}
func (pusService *PluginUsageStatsService)GetPluginUsageStatsDataSource(ctx context.Context) (res map[string][]map[string]any, err error) {
	res = make(map[string][]map[string]any)
	
	   plugin_id := make([]map[string]any, 0)
	   
       
       global.GVA_DB.Table("plugin_infos").Where("deleted_at IS NULL").Select("name as label,id as value").Scan(&plugin_id)
	   res["plugin_id"] = plugin_id
	   user_id := make([]map[string]any, 0)
	   
       
       global.GVA_DB.Table("sys_users").Where("deleted_at IS NULL").Select("username as label,id as value").Scan(&user_id)
	   res["user_id"] = user_id
	return
}
func (pusService *PluginUsageStatsService)GetPluginUsageStatsPublic(ctx context.Context) {
    // 此方法为获取数据源定义的数据
    // 请自行实现
}
